<?php

namespace App\Console\Commands;

use App\Project;
use App\AwardApplicationFormData;
use App\ProjectAttachment;
use App\Services\ConvertService;
use App\Services\FileService;
use App\Services\SmsService;
use App\Services\WordToPdfService;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class Wxl extends Command
{
    protected $signature = 'wxl';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->exportTalentAwardProjects();
    }

    private function exportTalentAwardProjects()
    {
        $projects = Project::where('award_id', 2)
            ->whereNotNull('project_name')
            ->whereNotIn('status_id', ['B1', 'B1.2', 'B3'])
            ->orderBy('created_at')
            ->get();
        $count = count($projects);
        $records = [];
        foreach ($projects as $i => $project) {
            $num = $i + 1;
            $this->log("$num/$count #{$project->id} {$project->project_name}");
            $formDataRecord = AwardApplicationFormData::find($project->id);
            $formData = json_decode($formDataRecord->form_data, true);
            $dateOfBirthString = $formData['basic']['birth'];
            try {
                $dateOfBirth = new Carbon($dateOfBirthString);
                $age = $dateOfBirth->diffInYears();
            } catch (\Exception $e) {
                $this->log("Bad date of birth: $dateOfBirthString");
                if (preg_match('#\d{4}#', $dateOfBirthString, $m)) {
                    $dateOfBirthString = "{$m[0]}-01-01";
                    $this->log("Extracted date: $dateOfBirthString");
                    $dateOfBirth = new Carbon($dateOfBirthString);
                    $age = $dateOfBirth->diffInYears();
                } else {
                    $age = null;
                }
            }
            $stats = [
                '实用新型数量' => 0,
                '发明专利数量' => 0,
                '软件著作权数量' => 0,
                '科研项目数量' => 0,
                '参与重大项目数量' => 0,
            ];
            foreach ($formData['property'] as $propertyItem) {
                $type = $propertyItem['property_category'];
                if (str_contains($type, '发明')) {
                    $stats['发明专利数量'] += 1;
                }
                if (str_contains($type, '实用新型')) {
                    $stats['实用新型数量'] += 1;
                }
                if (str_contains($type, '软件')) {
                    $stats['软件著作权数量'] += 1;
                }
            }
            $rdProjectFundingSum = 0;
            foreach ($formData['scientific'] as $projectItem) {
                $fundingValue = $projectItem['expenditure'];
                try {
                    $rdProjectFundingSum += $fundingValue;
                } catch (\Exception $e) {
                    $this->log("Bad project funding value: $fundingValue");
                    if (preg_match('#\d+#', $fundingValue, $m)) {
                        $fundingValue = $m[0];
                        $this->log("Extracted funding value: $fundingValue");
                        $rdProjectFundingSum += $fundingValue;
                    }
                }
            }
            $record = [
                '序号' => $num,
                '人选姓名' => $project->project_name,
                '年龄' => $age,
                '工作单位' => $formData['basic']['company'],
                '行政职务_专业职务' => $formData['basic']['duty'] . "\n" . $formData['basic']['professional'],
                '奖励或荣誉名称' => implode("\n", array_map(function ($item) {
                    return $item['award_name'];
                }, $formData['award'])),
                '论文_著作名称' => implode("\n", array_map(function ($item) {
                    return $item['paper_name'];
                }, $formData['paper'])),
                '实用新型数量' => $stats['实用新型数量'],
                '发明专利数量' => $stats['发明专利数量'],
                '软件著作权数量' => $stats['软件著作权数量'],
                '科研项目数量' => count($formData['scientific']),
                '研发经费总额' => (int)$rdProjectFundingSum,
                '参与重大项目数量' => count($formData['engineering']),
                '参与重大项目经济效益总额' => implode("\n", array_map(function ($item) {
                    return $item['economic'];
                }, $formData['engineering'])),
                '成果转化及推广' => $formData['situation'],
            ];
            $records[] = $record;
        }
        DB::statement('truncate _科技人物奖候选人情况汇总');
        DB::table('_科技人物奖候选人情况汇总')->insert($records);
    }

    private function notifyReviewersReviewStarted()
    {
        $smsSvc = new SmsService();
        $templateCode = config('sms.template_codes.评审开始通知');
        $rows = DB::select(
            'select reviewer_id, count(project_id) as project_count from reviewer_score_projects group by reviewer_id'
        );
        $rowCount = count($rows);
        foreach ($rows as $i => $row) {
            $rowNum = $i + 1;
            $reviewer = User::find($row->reviewer_id);
            if (!empty($reviewer->review_started_sms_notified_at)) {
                $this->log("$rowNum/$rowCount Reviewer #{$reviewer->id} {$reviewer->name} already notified");
                continue;
            }
            $this->log("$rowNum/$rowCount Notify reviewer #{$reviewer->id}");
            $tel = $reviewer->tel;
            $tel = '15927090286';
            $templateParamJson = json_encode([
                'name' => $reviewer->name,
                'projects' => $row->project_count,
                'username' => $reviewer->username,
                'password' => $reviewer->password,
            ], JSON_UNESCAPED_UNICODE);
            $this->log("Sms vars: $templateParamJson");
//            $smsSvc->sendTemplateSms($tel, $templateCode, $templateParamJson);
            $reviewer->update(['review_started_sms_notified_at' => now()]);
            $this->log("Sms sent");
//            return;
        }
    }

    private function testCreateSmsTasks()
    {
        $smsSvc = new SmsService();
        $phoneNumber = '15927090286,13657230392';
        $name = '孙工';
        $days = rand(1, 5);
        $projects = rand(10, 20);
        $this->log("Creating test sms tasks: $phoneNumber, $name, $days, $projects");
        $task = $smsSvc->createReviewStartedSmsTask($phoneNumber, $name, $projects);
        $task = $smsSvc->createReviewMiddleTermSmsTask($phoneNumber, $name, $projects);
        $task = $smsSvc->createReviewEndingSmsTask($phoneNumber, $name, $days, $projects);
        return;
        if ($success) {
            $this->log("Success");
        } else {
            $this->log("Error: " . $smsSvc->getLastErrorMessage());
        }
    }

    private function testSyncAttachments()
    {
        $fileSvc = new FileService();
        $projects = Project::whereNotIn('status_id', ['B1', 'B1.2'])
            ->where('attachment_processed', 0)
            ->get();
//        $projects = Project::whereIn('id', [731])->get();
        foreach ($projects as $project) {
            $this->log("project #{$project->id}");
            $fileSvc->syncProjectAttachmentsFromFormData($project);
        }
    }

    private function testPdfConvert()
    {
        $wordFile = public_path('storage/talent.docx');
        $pathinfo = pathinfo($wordFile);
        $pdfFile = public_path('storage/' . $pathinfo['filename'] . '.pdf');
        $this->convertWordDocToPdf($wordFile, $pdfFile);
    }

    private function convertWordDocToPdf($wordFile, $pdfFile)
    {
        $convertSvc = new WordToPdfService();
        $convertSvc->convert($wordFile, $pdfFile);
    }

    private function exportProjectAppFormWordDoc($projectId)
    {
        $project = Project::find($projectId);

        $taskId = null;
        $formData = AwardApplicationFormData::find($project->id)->form_data;
        echo $formData;
        exit;

        $resultPath = '/storage';
        $barcode = date('YmdHis');

        $convertSvc = new ConvertService();
        $convertSvc->convertAwardFormDataToWordDocument($taskId, $formData, $project->award_id, $project->award_id == 1 ? 'progress' : 'talent', $resultPath, $barcode);

    }

    private function log($msg)
    {
        $now = now();
        $line = "[$now]$msg";
        $this->line($line);
    }
}
